# 先导入内置模块（无）

# 再导入第三方模块
from django.conf import settings
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.shortcuts import render, redirect


# 最后导入自定义模块
from web import models
from day06.utils.response import BaseResponse
from web.forms.account import SmsLoginForm, LoginForm, MobileForm


def login(request):
    """用户名密码登录视图函数"""
    if request.method == "GET":
        form = LoginForm()
        return render(request, "login.html", {"form": form})

    # 1. 接收并获取数据(数据格式及是否为空校验)
    if request.method == "POST":
        form = LoginForm(data=request.POST)
        if not form.is_valid():
            return render(request, "login.html", {"form": form})

        # 2.去数据库校验
        data_dict = form.cleaned_data
        role = data_dict.pop('role')
        if role == '1':
            user_obj = models.Administrator.objects.filter(active=1).filter(**data_dict).first()
        else:
            user_obj = models.Customer.objects.filter(active=1).filter(**data_dict).first()

        # 2.1 校验失败
        if not user_obj:
            form.add_error("password", "用户名或密码错误")
            return render(request, "login.html", {"form": form})

        # 2.2 校验成功，用户信息写入 session + 跳转到管理界面
        mapping = {"1": "ADMIN", "2": "CUSTOMER"}
        request.session[settings.WL_SESSION_KEY] = {'role': mapping[role], 'name': user_obj.username, 'id': user_obj.id}
        return redirect(settings.WL_LOGIN_HOME)


def sms_send(request):
    """发送短信视图函数"""
    res = BaseResponse()

    # 1. 验证数据的合法性：手机号格式+角色
    form = MobileForm(data=request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 1.5 校验手机号是否存在
    mobile = form.cleaned_data['mobile']
    role = form.cleaned_data['role']

    if role == '1':
        exists = models.Administrator.objects.filter(active=1, mobile=mobile).exists()
    else:
        exists = models.Customer.objects.filter(active=1, mobile=mobile).exists()

    if not exists:
        res.detail = {"mobile": ["手机号不存在"]}
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 2.发送短信 + 生成验证码
    # 这里用默认的验证码，没有条件申请
    sms_code = '1234'
    mobile = form.cleaned_data['mobile']

    # 3. 将手机号和验证码保存（便于后续校验）保存到 redis 中
    conn = get_redis_connection("default")
    conn.set(mobile, sms_code, ex=60)

    res.status = True
    return JsonResponse(res.dict)


def sms_login(request):
    """短信登录视图函数"""
    if request.method == "GET":
        form = SmsLoginForm()
        return render(request, "sms_login.html", {"form": form})
    if request.method == "POST":
        res = BaseResponse()

        # 1.手机号格式校验
        form = SmsLoginForm(request.POST)
        if not form.is_valid():
            res.detail = form.errors
            return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

        # 2.短信验证码 和 redis 的验证码  做校验
        mobile = form.cleaned_data['mobile']
        code = form.cleaned_data['code']
        role = form.cleaned_data['role']

        conn = get_redis_connection("default")
        cache_code = conn.get(mobile)
        # print(cache_code)
        if not cache_code:
            res.detail = {"code": ["短信验证码未发送或失效"]}
            return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

        if code != cache_code.decode('utf-8'):
            res.detail = {"code": ["短信验证码错误"]}
            return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

        # 3. 登录成功 + 注册
        if role == '1':
            user_obj = models.Administrator.objects.filter(active=1, mobile=mobile).first()
        else:
            user_obj = models.Customer.objects.filter(active=1, mobile=mobile).first()
        if not user_obj:
            res.detail = {"mobile": ["手机号不存在"]}
            return JsonResponse(res.dict)

        # 信息写入session
        mapping = {"1": "ADMIN", "2": "CUSTOMER"}
        request.session[settings.WL_SESSION_KEY] = {'role': mapping[role], 'name': user_obj.username, 'id': user_obj.id}
        res.status = True
        res.data = settings.WL_LOGIN_HOME
        return JsonResponse(res.dict)


def logout(request):
    """登出视图函数"""
    request.session.clear()
    return redirect(settings.WL_LOGIN_URL)


def home(request):
    """首页视图函数"""
    return render(request, 'home.html')


# def level(request):
#     """级别视图函数"""
#     return render(request, 'level.html')


# def user(request):
#     """用户视图函数"""
#     return render(request, 'user.html')


# def order(request):
#     """订单视图函数"""
#     return render(request, 'order.html')


# def order_add(request):
#     """创建订单视图函数"""
#     return render(request, 'order_add.html')
